import {createRouter,createWebHashHistory} from 'vue-router'
import Category from '../views/category/index.vue'
import Product from '../views/product/index.vue'
import User from '../views/user/index.vue'
import CateList from '../views/category/list.vue'
import CatePub from '../views/category/pub.vue'
import TestPinia from '../views/test-pinia/index.vue'
import CompA from '../views/test-pinia/comp-a.vue'
import CompB from '../views/test-pinia/comp-b.vue'
import Register from '../views/user/register.vue'
import Login from '../views/user/login.vue'
import MainLayout from '../layout/index.vue'
import { useAccount } from '../store/user'

//路由映射关系（路径---组件）
export const myRoutes = [
    {
        path:'/',
        component:MainLayout,
        // meta:{title:'分类管理'},
        children:[
            {
                path:'/cate',
                component:Category,
                meta:{title:'分类管理'},
                children:[
                    {
                        path:'pub',  //不带/，代表相对路径，需要通过/cate/pub访问此路由
                        component:CatePub,
                        meta:{title:'发布分类'},
                    },
                    {
                        path:'list',
                        component:CateList,
                        meta:{title:'分类列表'},
                    }
                ]
            },
            {path:'/pro',component:Product,meta:{title:'商品管理'}},
            {
                path:'/user',
                component:User,
                meta:{title:'账号管理'},
                children:[
                    {
                        path:'reg',  
                        component:Register,
                        meta:{title:'分配账号'},
                    }
                ]
            },
            {
                path:'/test/pinia',
                component:TestPinia,
                meta:{title:'测试pinia'},
                children:[
                    {
                        path:'a',  //不带/，代表相对路径，需要通过/cate/pub访问此路由
                        component:CompA,
                        meta:{title:'A页面'},
                    },
                    {
                        path:'b',
                        component:CompB,
                        meta:{title:'B页面'},
                    }
                ]
            },
        ]
    },
    {
        path:'/login',
        component:Login,
        meta:{title:'用户登录'}
    }
]

export const a = 123

//创建路由对象
const router = createRouter({
    history:createWebHashHistory(), //哈希模式、history模式
    routes:myRoutes
})

//全局前置守卫

router.beforeEach((to,from,next)=>{
    console.log('to',to);
    console.log('from',from);
    let whiteList = ['/login']  //白名单
    if(whiteList.includes(to.path)){
        next()  //白名单路由，直接放行
    }
    // 用户是否登录
    const account = useAccount()
    if(account.userInfo){
        next()   //已登录用户可以放行
    }
    next('/login')  //拦截访问至登录页
})

// 对外抛出路由对象
export default router


